import { Dialog } from 'vant';
import axios from 'axios';
import { Toast } from 'mint-ui';
export default{
    state: {
      shopping:[],
      list:[]
    },
    getters: {
      isCkeckedAll(state){
        return state.list.length ===state.shopping.length
      },
      total(state){
          let totals ={
            num:0,
            price:0
          }
          state.shopping.map(element => {
            if(element.checked){
              totals.num += parseInt(element.num);
              totals.price +=parseInt(element.num) * element.price
            } 
          });
          return totals
      }
    },
    mutations: {
      cart(state,obj){
        state.shopping=obj
        state.list=state.shopping.map(v=>{
          return v.id
        })
      },
      check_all(state){
        state.shopping.map(element => {
          element.checked = true
          state.list.push(element.id)
        });
      },
      unchecked_all(state){
        state.shopping.map(element => {
          element.checked = false
        });
        state.list=[]
      },
      checkOne(state,id){
        let i=state.list.indexOf(id)
        if(i>-1){
         return state.list.splice(i,1)
        }
        state.list.push(id)
      },
      deleteOne(state,id){
        Dialog.alert({
          showCancelButton:true,
          message: '确定要删除吗',
        }).then(() => {
          axios({
            url:'/ajax/delete',
            method:'post',
            data:{
              id
            }
          }).then(({data})=>{
            const index=state.shopping.findIndex(p=>p.id===id)
            state.shopping.splice(index,1)
            if(data.success){
              Toast(data.msg)
            }
          })
        }).catch(()=>{
          
        });
      }
    },
    actions: {
      checkAllFn({commit,getters}){
        getters.isCkeckedAll ? commit('unchecked_all') : commit('check_all')
      }
    }
  }